package com.zhouyu.mysql.core;

import com.zhouyu.mysql.dict.DictTable;
import com.zhouyu.mysql.dict.SystemDict;
import com.zhouyu.mysql.page.FspHdrPage;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import static com.zhouyu.mysql.core.PageUtil.PAGE_SIZE;

/**
 * 大都督周瑜（我的私人微信: dadudu6789）
 */
public class SpaceUtil {


    public static Path createUserTableSpace(String tableName) {
        Path path = Paths.get(tableName + ".ibd");

        if (!Files.exists(path)) {
            byte[] bytes = new byte[1 * PAGE_SIZE];
            try {
                Files.write(path, bytes, StandardOpenOption.CREATE_NEW);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return path;
    }

    public static FspHdrPage getFspHdrPage(int spaceId) {
        Path path = getPathBySpaceId(spaceId);
        try (FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.READ)) {
            ByteBuffer byteBuffer = ByteBuffer.allocate(PAGE_SIZE);
            fileChannel.position(0); // FspHdrPage是表空间的第0页
            fileChannel.read(byteBuffer);

            FspHdrPage page = new FspHdrPage();
            page.setPageByteBuffer(byteBuffer);
            return page;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取指定表空间的下一个空闲页号
     *
     * @param spaceId 表空间id
     * @return 页号
     */
    public static int getNextPageNo(int spaceId) {
        FspHdrPage hdrPage = getFspHdrPage(spaceId);
        int pageNo = hdrPage.get_fsp_size();
        hdrPage.set_fsp_size(pageNo + 1);
        PageUtil.flushPage(hdrPage);  // 修改了FspHdrPage，直接持久化
        return pageNo;
    }

    public static Path getPathBySpaceId(int spaceId) {
        DictTable dictTable = SystemDict.getInstance().getSpaceIdTables().get(spaceId);
        return Paths.get(dictTable.getPath());
    }


}
